package jwt

import (
	"time"

	"goweb/utils/commons"

	"goweb/ext/e"
	"goweb/ext/settings"

	jwt "github.com/dgrijalva/jwt-go"
)

var jwtSecret = []byte(conf.JwtBase.JwtSecret)

type Claims struct {
	UserName string `json:"UserName"`
	Uid      string `json:"Uid"`
	SourceId string `json:"Source"` //sourceid里面包含sourceId和是否合并token
	jwt.StandardClaims
}

func GenerateToken(uid, utime string, Source string) (string, error) {

	nowTime := time.Now()
	//过期时间三小时
	//time.Duration(conf.ServerBase.ReadTimeOut) * time.Second
	expireTime := nowTime.Add(time.Duration(conf.JwtBase.Expire) * time.Hour)

	claims := Claims{
		utime,
		uid,
		Source,
		jwt.StandardClaims{
			//NotBefore://签名生效时间
			ExpiresAt: expireTime.Unix(), //过期时间
			Issuer:    "web",             //签名的发行者
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(jwtSecret)
	return token, err
}

func ParseToken(token string) (*Claims, error, int) {
	code := e.ERROR_TOKEN
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})

	if !commons.CheckErr(err) {
		return nil, err, code
	}

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil, e.SUCCESS
		}
	}

	if !tokenClaims.Valid {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				code = e.ERROR_TOKEN
			} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
				code = e.ERROR_AUTH_TOKEN_TIMEOUT
			}
		}
	}

	return nil, err, code
}
